import { Component, ChangeDetectorRef, ChangeDetectionStrategy, Input } from '@angular/core';
import * as _ from 'lodash';
import { ActivatedRoute } from '@angular/router';
import { SubIndustryModel } from '../../templates/subIndustry/subIndustry.model';
import { CompanyRiskRatingService } from '../../companyRiskRating.service';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { UtilsService } from '../../../../../../shared/services/utils.service';
import { SubIndustryBenchmarkModel, UniverseBenchmarkModel, IndustryBenchmarkModel, MeiBenchmarkModel } from '../../models/riskBenchmark.model';
import { RiskExposureModel } from '../../models/riskExposure.model';
import { ChartBenchmarkModel } from '../../templates/subIndustry/models/chartBenchmark.model';
import { ChartExposureModel } from '../../../../../../shared/models/chartExposure.model';
import { ClusterService } from '../../../../riskCluster/cluster.service';

/**
 * MEI sub industry component
 *
 * Author: Sorin Spiru
 * Date: 16.01.2018
 */
@Component({
    selector: 'mei-subindustry-risk-rating',
    templateUrl: '../../templates/subIndustry/subIndustry.component.html',
    styleUrls: [
        '../../../company.component.scss',
        '../../companyRiskRating.component.scss',
        '../../templates/subIndustry/subIndustry.component.scss'
    ],
    providers: [UtilsService],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class SubIndustryMeiComponent extends SubIndustryModel {
    private sub: Subscription;
    private companySub: Subscription;
    private meiSub: Subscription;
    private forkSub: Subscription;

    public formatRank = UtilsService.formatRank;
    public company;
    public meiBenchmark: MeiBenchmarkModel;
    public ratingDistributionChartColors: { color: string; alpha: number; }[];
    @Input() displayType = 'distribution';

    constructor(
        private route: ActivatedRoute,
        private cdRef: ChangeDetectorRef,
        private riskService: CompanyRiskRatingService,
        private clusterService: ClusterService) {
        super(cdRef);
        this.primaryName = "Subindustry";
        this.ratingDistributionChartColors = [
            {color: "#CCCCCC", alpha: 1},
            {color: "#175f96", alpha: 0.5},
            {color: "#175f96", alpha: 1}
         ];
    }

    ngOnInit() {
        this.maxManagement = 100;
        this.maxExposure = 20;
        this.sub = this.route.params.subscribe(params => {
            this.load();
        });
    }

    ngOnDestroy() {
        this.sub.unsubscribe();
        if(this.companySub) this.companySub.unsubscribe();
        if(this.meiSub) this.meiSub.unsubscribe();
        if(this.forkSub) this.forkSub.unsubscribe();
    }

    private load(): void {
        this.loaded = new Promise<void>((resolve, reject) => {
            this.companySub = this.riskService.company.subscribe(company => {
                this.meiSub = this.riskService.mei.subscribe(mei => {
                    this.subIndustryAverageExposure = mei.subIndustryAverageExposure;
                    this.subIndustryAverageManagement = mei.subIndustryAverageManagement;
                    this.company = company;
                    this.currentCompany = company.id;
                    this.currentCompanyName = company.companyName;
                    this.companyClusterCode = mei.assessmentCode;
                    this.clusterService.mei.subscribe(clusters => {
                        this.riskClusters = clusters;

                        let promises = [this.riskService.meiIndustryBenchmark, this.riskService.meiIndustryExposure];
                        if(this.displayType == 'scatter')
                        {
                            if(mei.type == 'BaselineIssue')
                                promises.push(this.riskService.getBaselineExposure());
                            else
                                promises.push(this.riskService.meiExposure);
                        }

                        this.forkSub = Observable.forkJoin(promises).subscribe(data => {
                            this.meiBenchmark =  data[0] as MeiBenchmarkModel;
                            this.scatter = data[1] as RiskExposureModel[];
                            this.universe =  {
                                chartData: this.meiBenchmark.chartDataUniverse,
                                performance: this.meiBenchmark.universePerformance
                            } as UniverseBenchmarkModel;

                            this.industry =  {
                                chartData: this.meiBenchmark.chartDataIndustry,
                                performance: this.meiBenchmark.industryPerformance,
                                peersList: this.meiBenchmark.peersList
                            } as IndustryBenchmarkModel;

                            this.subIndustry =  {
                                chartData: this.meiBenchmark.chartDataSubIndustry,
                                performance: this.meiBenchmark.subIndustryPerformance,
                                peersList: this.meiBenchmark.peersList
                            } as SubIndustryBenchmarkModel;

                            if(this.displayType == 'scatter')
                            {
                                this.universeExposure = data[2] as RiskExposureModel[];
                                //scatter chart data
                                let companyBullet: ChartExposureModel;
                                let scatterResult: ChartExposureModel[] = [];
                                this.scatter.forEach(subGroupMei => {
                                    companyBullet = new ChartExposureModel(
                                        subGroupMei.management,
                                        subGroupMei.exposure,
                                        this.clusterService.ClusterMetadata[subGroupMei.cluster].color,
                                        subGroupMei.companyName
                                    );

                                    this.subIndustry.peersList.forEach(peer => {
                                        if (peer.companyId == subGroupMei.companyId) {
                                            companyBullet.peerPosition = peer.rank;
                                            if (subGroupMei.companyId == company.id) {
                                                companyBullet.currentX = companyBullet.X;
                                                companyBullet.currentY = companyBullet.Y;
                                            }
                                            else {
                                                companyBullet.peerX = companyBullet.X;
                                                companyBullet.peerY = companyBullet.Y;
                                            }
                                            return;
                                        }
                                    });
                                    scatterResult.push(companyBullet);
                                });
                                this.universeExposure.forEach(peer=>{
                                    if(peer.companyId != company.id)
                                    {
                                        let universe = new ChartExposureModel(undefined, undefined)
                                        universe.peerX = peer.exposure;
                                        universe.peerY = peer.management;
                                        universe.name = peer.companyName;
                                        scatterResult.push(universe);
                                    }
                                });
                                this.exposureData = scatterResult;
                            }
                            else
                            {
                                this.universeExposure = [];
                                this.universe.performance.percentile = Math.round(this.universe.performance.percentile * 100);
                                this.industry.performance.percentile = Math.round(this.industry.performance.percentile * 100);
                                this.subIndustry.performance.percentile = Math.round(this.subIndustry.performance.percentile * 100);
                                //benchmark chart data
                                let benchmarkResult: ChartBenchmarkModel[] = []                            
                                for (var i = 0; i < this.riskClusters.length; i++) {
                                    benchmarkResult.push({
                                        score: this.subIndustry.chartData[i].xValue,
                                        primary: this.universe.chartData[i].yValue,
                                        secondary: this.industry.chartData[i].yValue,
                                        tertiary: this.subIndustry.chartData[i].yValue,
                                    });
                                }
                                this.benchmarkData = benchmarkResult;
                            }
                            this.cdRef.markForCheck();
                            resolve();
                        }, error => this.errorCallback(_ => this.errorReset(), error));
                    });

                }, error => this.errorCallback(_ => this.errorReset(), undefined));
            });
        });
    }
}